﻿using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;
using System.Net.Http.Headers;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetSaleReceiptCommandHanders : IRequestHandler<GetSaleReceiptCommands, APIPaging<List<SalesReceipt>>>
    {
        public IBaseRepository<SalesReceipt> baseRepository;

        public GetSaleReceiptCommandHanders(IBaseRepository<SalesReceipt> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 显示销售出库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<SalesReceipt>>> Handle(GetSaleReceiptCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<SalesReceipt>> result = new APIPaging<List<SalesReceipt>>() { };
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            var sql = "select * from SalesReceipt where IsDelete=false ORDER BY SalesReceiptId DESC";
            var list = await baseRepository.SelectAsync(sql);
            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                list = list.Where(x => x.CustomerName.Contains(request.CustomerName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.OutboundOrderCode))
            {
                list = list.Where(x => x.OutboundOrderCode.Contains(request.OutboundOrderCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SalesOrderNumber))
            {
                list = list.Where(x => x.SalesOrderNumber.Contains(request.SalesOrderNumber)).ToList();
            }
            if (request.OutboundDate != null)
            {
                list = list.Where(x => x.OutboundDate == request.OutboundDate).ToList();
            }
            if (request.DocumentStatus > 0)
            {
                list = list.Where(x => x.DocumentStatus == request.DocumentStatus).ToList();
            }
            result.TotalCount= list.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            list=list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data= list;
            return result;
        }
    }
}
